﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using CY_MVC.Utility;
using System.Linq;

namespace CY_MVC.Core
{
    #region WordFilterHelper

    //UrlRewrite工具类
    //要在web.config的AppSettings里面设置字段UrlRewriteRulesPath为UrlRewrite规则的路径

    public static class WordFilterHelper
    {
        private static List<WordFilterRule> WordFilterRules = new List<WordFilterRule>();

        public static void Init()
        {
            if (string.IsNullOrEmpty(StaticConfig.WordFilterRulesPath)) return;
            WordFilterRules = XmlDataHelper.LoadFile<List<WordFilterRule>>(StaticConfig.WordFilterRulesPath) ??
                                new List<WordFilterRule>();
            WordFilterRules = new List<WordFilterRule>(WordFilterRules.OrderByDescending(p => p.Word2Filter));
        }

        public static void SetRulesList(List<WordFilterRule> p_WordFilterRules)
        {
            if (p_WordFilterRules == null)
            {
                throw new Exception("过滤关键词列表为空!");
            }
            WordFilterRules = p_WordFilterRules;
            XmlDataHelper.SaveFile(p_WordFilterRules, StaticConfig.WordFilterRulesPath);
            WordFilterRules = new List<WordFilterRule>(WordFilterRules.OrderByDescending(p => p.Word2Filter));
        }

        public static string WordFilter(string p_ViewStr)
        {
            if (!string.IsNullOrEmpty(StaticConfig.WordFilterRulesPath))
            {
                p_ViewStr = WordFilterRules.Aggregate(p_ViewStr, (p_Current, p_Item) => p_Item.RegexWord.Replace(p_Current, p_Item.ShowWord));
            }
            return p_ViewStr;
        }

    }

    #endregion

    #region WordFilterRule

    //WordFilter规则
    [Serializable]
    [XmlRoot]
    public class WordFilterRule
    {

        [XmlAttribute]
        public string Word2Filter { get; set; }

        private string m_ShowWord;
        [XmlAttribute]
        public string ShowWord
        {
            get
            {
                return string.IsNullOrEmpty(m_ShowWord) ? "[过滤词]" : m_ShowWord;
            }
            set { m_ShowWord = value; }
        }

        private Regex m_RegexWord;
        public Regex RegexWord
        {
            get
            {
                return m_RegexWord ??
                       (m_RegexWord = new Regex(Word2Filter, RegexOptions.Compiled | RegexOptions.IgnoreCase));
            }
        }
    }

    #endregion
}
